<template>
  <div class="x-input-container" :style="{ width: width + 'px' }">
    <input
      class="x-input"
      :value="value"
      ref="input"
      @input="$emit('input', $event.target.value)"
      :class="{ default: !error, error }"
      :type="type"
      :style="{ width: width + 'px' }"
    />

    <div v-if="showIcon" class="show-icon show" @click="changeType">
      <img :src="iconPathList[0]" v-if="showFirst" />
      <img :src="iconPathList[1]" v-else />
    </div>

    <div v-show="error" class="error-message">
      {{ error }}
    </div>
  </div>
</template>

<script>
  export default {
    name: 'XInput',
    props: {
      value: {
        type: String,
        default: '',
      },
      type: {
        type: String,
        default: 'text',
      },
      width: {
        type: Number,
        default: 300,
      },
      rules: {
        type: Array,
        default: () => [],
      },
    },

    data() {
      return {
        error: '',
        showIcon: this.type === 'password' ? true : false,
        iconPathList: ['/images/show.svg', '/images/hide.svg'],
        showFirst: true,
      }
    },
    methods: {
      errorCallback(message) {
        this.error = message
      },
      changeType() {
        if (this.$refs.input.type === 'password') {
          this.showFirst = false
          this.$refs.input.type = 'text'
        } else {
          this.showFirst = true
          this.$refs.input.type = 'password'
        }
      },
      oppenLisener(listenType, callback) {
        this.$refs.input.addEventListener(listenType, callback)
      },
    },
    watch: {
      value() {
        this.error = ''
      },
    },

    mounted() {
      this.$emit('send-error-callback', this.errorCallback)
    },
  }
</script>

<style lang="scss" scoped>
  @import '../config.scss';

  /* 隐藏密码输入框中的小眼睛图标 */
  input[type='password']::-webkit-contacts-auto-fill-button,
  input[type='password']::-webkit-credentials-auto-fill-button,
  input[type='password']::-ms-reveal {
    display: none;
  }

  .x-input-container {
    position: relative;
    box-sizing: border-box;
  }

  .x-input {
    box-sizing: border-box;
    width: 290px;
    height: 50px;
    border: none;
    background: none;
    padding-left: 18px;
    outline: none;
    font-size: 14px;
    border-radius: $border-radius;
  }

  .default {
    border: 1px solid rgba(216, 224, 240, 1);
    &:focus {
      border-color: $active-color;
      box-shadow: 0px 0px 0px 3px rgba(63, 140, 255, 0.12);
    }

    &:disabled {
      background-color: $disabled-color;
      cursor: not-allowed;
    }
  }

  .error {
    border: 1px solid $error-color;
  }

  .error-message {
    position: absolute;
    height: 17px;
    line-height: 17px;
    font-size: 12px;
    color: $error-color;
    bottom: -20px;
    left: 18px;
    width: 100%;
  }
  .show-icon {
    position: absolute;
    width: 24px;
    height: 24px;
    top: 13px;
    right: 18px;
    cursor: pointer;
  }
</style>
